package com.whu.MenuHub.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.whu.MenuHub.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserDao extends BaseMapper<User> {

    //根据用户名获取信息
    @Select("select * from user where username = #{userName}")
    public User getUserByUserName(String userName);

    //新增一个用户信息，并且实现id回填
    @Insert("INSERT INTO user (username,password,role,level,avatar,gender,nativeplace,birthday) " +
            "VALUES (#{username},#{password},#{role},#{level},#{avatar},#{gender},#{nativeplace},#{birthday})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id",
            keyColumn = "id", resultType = Integer.class, before = false)
    void insertUser(User user);

    //分页获取用户信息
    @Select("SELECT * FROM user ${ew.customSqlSegment}")
    public IPage<User> findUsers(IPage<User> page,
                                          @Param(Constants.WRAPPER) QueryWrapper<User> wrapper);

    //获取历史最活跃用户
    @Select("select user.* from `user`,orders " +
            "where user.id=orders.userID GROUP By `user`.id order by count(orders.id) DESC LIMIT 5")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "orderNum", column = "id",
                    one = @One(select = "com.whu.MenuHub.dao.OrderDao.getOrderNumByUserID")),
    })
    //获取历史最活跃的用户
    List<User> getHistoryActiveUser();


    //获取近期最活跃用户
    @Select("select user.* from `user`,orders " +
            "where user.id=orders.userID and DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= orders.orderTime " +
            "GROUP By `user`.id order by count(orders.id) DESC LIMIT 5")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "orderNum", column = "id",
                    one = @One(select = "com.whu.MenuHub.dao.OrderDao.getRecentOrderNumByUserID")),
    })
    List<User>getRecentActiveUser();

    @Select("SELECT count(*) from `user` where id<#{userID}")
        //获取用户在表中的排序
    int getRankNum(Integer userID);
}
